import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/event/click_carplate_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/main/page/address_page.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/event/click_user_info_event.dart';
import 'package:flutter_rider/event/click_address_event.dart';
import 'package:flutter_rider/utils/alib.dart';
import 'package:flutter_svg/flutter_svg.dart';

import '../../../api/api.dart';
import '../../../event/refresh_map_event.dart';
import '../../../event/refresh_order_event.dart';
import '../../../generated/r.dart';
import '../../../main/widgets/dialog/loading_dialog.dart';
import '../../../main/widgets/pop/pop_carplate_list.dart';
import '../../../utils/toast.dart';

class AddressInfoPage extends StatefulWidget {
  String stationName;
  String stationId;
  int aliasId;
  String aliasName;
  String username;
  String phone;
  String address;
  String addrDesc;
  String carPlate;
  int missionNum;
  String no;
  AddressInfoPage(
      this.stationName,
      this.stationId,
      this.aliasId,
      this.aliasName,
      this.username,
      this.phone,
      this.address,
      this.carPlate,
      this.addrDesc,
      this.missionNum,
      this.no,
      {Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return UserInfoPageState();
  }
}

class UserInfoPageState extends State<AddressInfoPage> {
  late StreamSubscription _eventFn;
  late StreamSubscription _eventFn1;
  final _nameTextController = TextEditingController();
  final _phoneTextController = TextEditingController();
  final _addDescTextController = TextEditingController();
  final _carNoTextController = TextEditingController();
  String _stationName = "";
  String _stationId = "";
  String _aliasName = "";
  int _aliasId = 0;
  String _address = "";

  @override
  void initState() {
    super.initState();
    _nameTextController.text = widget.username;
    _phoneTextController.text = widget.phone;
    _address = widget.address;
    _addDescTextController.text = widget.addrDesc;
    var regex = RegExp(r'\n');
    String carPlate = widget.carPlate.replaceAll(regex, " \n ");
    _carNoTextController.text = carPlate;

    // final count = ref.watch(counterProvider);

    _eventFn = eventBus.on<ClickAddressEvent>().listen((event) {
        setState(() {
          _stationName =event.stationName !="" ? event.stationName : widget.stationName ;
          _stationId = event.stationId !="" ? event.stationId : widget.stationId ;
          String stationName = event.aliasName!=""?"(" + event.stationName + ")":event.stationName;
          _address = event.aliasName !="" || event.stationName != ""? event.aliasName +  stationName: widget.address;
          _aliasName = event.aliasName !=""? event.aliasName : widget.aliasName;
          _aliasId = event.aliasId !=0?event.aliasId : widget.aliasId;
        });
    });

    _eventFn1 = eventBus.on<ClickCarPlateEvent>().listen((event) {
      _carNoTextController.text = event.carplate == ""?carPlate:event.carplate;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn.cancel();
    _eventFn1.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          Alib.hideKeyboard(context);
        },
        child:Material(
          color: UIColor.color_main,
          child: Column(
              children: [
                _renderTitle(),
                Container(
                  padding: EdgeInsets.only(top: 12.rpx,right: 12.rpx,left: 12.rpx),
                  decoration: const BoxDecoration(
                   color: UIColor.color_content,
                  ),
                  child: Column(
                    children: [
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderName(),
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderPhone(),
                        Container(
                            height: 0.5.rpx,
                            color: UIColor.color_divider),
                        _renderAddress(),
                      Container(
                          height: 0.5.rpx,
                          color: UIColor.color_divider),
                      _renderAddDesc(),
                      Container(
                          height: 0.5.rpx,
                          color: UIColor.color_divider),
                      _renderCarPlate(),
                    ]
                  )
                ),
                32.hspace,
                Padding(
                  padding: EdgeInsets.all(12.rpx),
                  child: UText.getBkButton(
                    "提交",
                    16.rpx,
                    bkColor: UIColor.color_primary,
                    radius: 24.rpx,
                    width: double.infinity,
                    height: 48.rpx,
                    onPressed: _onClickSubmit,
                  ),
                ),
          ])
        )
    );
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child:Stack(
        children: [
          SizedBox(width: 50.rpx, child: IconButton(
            iconSize: 18.rpx,
            icon: const Icon(
              Icons.arrow_back_ios_new,
              color: UIColor.color_t1,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),),
          Center(
              child: UText.get("收货信息", Colors.black, 16.rpx, fw: FontWeight.w600).center
          ),
        ],
      ),
    );
  }

  Widget _renderName() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get("收货人", UIColor.color_t5, 14.rpx)
            ),
            Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
                  controller: _nameTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  decoration:   InputDecoration(
                    hintText: "请输入收货人",
                    border:InputBorder.none,
                    hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.26),fontSize: 15,),
                  )
              ),
            ),
          ]
      ),
    );
  }

  Widget _renderPhone() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get("收货电话", UIColor.color_t5, 14.rpx)
            ),
            Expanded(
                child: TextField(
                    style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
                    controller: _phoneTextController,
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                    ],
                    maxLength: 11,
                    decoration:  InputDecoration(
                      counterText: "",
                      hintText: "请输入收货电话",
                      border:InputBorder.none,
                      hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.26),fontSize: 15,),
                    )
                )
            )
          ]
      ),
    );
  }

  Widget _renderAddress() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
        children: [
          SizedBox(
              width: 80.rpx,
              child: UText.get("收货地址", UIColor.color_t5, 14.rpx)
          ),
          Expanded(
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    OpenUtils.open(
                        context,
                        AddressPage(1, widget.no,
                            widget.missionNum)
                    );
                  },
                  child: Row(
                      children: [
                        LimitedBox(
                          maxWidth: 240.rpx,
                          child:
                          Text(_address == ""?"请选择收货地址":_address, style: TextStyle(color:_address == ""?UIColor.color_t5:UIColor.color_t1,fontSize: 14.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),
                        ),
                        const Spacer(),
                        SvgPicture.asset(R.image_chevron_right, width: 20.rpx, height: 20.rpx),
                      ]
                  )
              )
          ),
          // Expanded(
          //     child: TextField(
          //         style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
          //         controller: _addressTextController,
          //         keyboardType: TextInputType.multiline,
          //         maxLines: null,
          //         maxLength: 11,
          //         decoration: const InputDecoration(
          //           counterText: "",
          //           hintText: "请选择收货地址",
          //           border:InputBorder.none,
          //           hintStyle: TextStyle(fontSize: 15),
          //         )
          //     )
          // ),
          // SizedBox(
          //     width: 80.rpx,
          //     child:  GestureDetector(
          //         behavior: HitTestBehavior.opaque,
          //         onTap: () {
          //           OpenUtils.open(
          //               context,
          //               AddressPage(2, widget.no,
          //               widget.missionNum)
          //           );
          //         },
          //         child:Row(
          //           mainAxisAlignment: MainAxisAlignment.end,
          //           children: [
          //             SvgPicture.asset(R.image_chevron_right, width: 20.rpx, height: 20.rpx),
          //           ],
          //         )
          //
          //     )
          // )
        ],
      ),
    );
  }

  Widget _renderAddDesc() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
          children: [
            SizedBox(
                width: 80.rpx,
                child: UText.get("详细描述", UIColor.color_t5, 14.rpx)
            ),
            Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
                  controller: _addDescTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  decoration:   InputDecoration(
                    hintText: "请输入详细描述",
                    border:InputBorder.none,
                    hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.26),fontSize: 15,),
                  )
              ),
            ),
          ]
      ),
    );
  }

  Widget _renderCarPlate() {
    return SizedBox(
      height: 48.rpx,
      child:Row(
        children: [
          SizedBox(
              width: 80.rpx,
              child: UText.get("收货车牌", UIColor.color_t5, 14.rpx)
          ),
          Expanded(
              child: TextField(
                  style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
                  controller: _carNoTextController,
                  keyboardType: TextInputType.multiline,
                  maxLines: null,
                  maxLength: 11,
                  decoration:  InputDecoration(
                    counterText: "",
                    hintText: "车牌号，如：川A88888",
                    border:InputBorder.none,
                    hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.26),fontSize: 15,),
                  )
              )
          ),
          Container(
              width: 50.rpx,
              decoration: const BoxDecoration(
                border: Border(
                    left: BorderSide(width: 0.5, color: UIColor.color_divider)
                ),
              ),
              child:  GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  OpenUtils.pop2(context,   PopCarPlaterUserList(_stationName == ""? widget.stationName : _stationName));
                },
                child:Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    SvgPicture.asset(R.image_note, width: 24.rpx, height: 24.rpx),
                  ],
                )

            )
          )
        ],
      ),
    );
  }

  _onClickSubmit() {
    if (_nameTextController.text == "") {
      Tip.show("请输入收货人");
      return ;
    }
    if (_phoneTextController.text == "") {
      Tip.show("请输入收货电话");
      return ;
    }
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (!exp.hasMatch(_phoneTextController.text)) {
      Tip.show("请输入正确格式的收货电话");
      return ;
    }
    if (_address == "") {
      Tip.show("请选择收货地址");
      return ;
    }
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
            backgroundColor:Colors.transparent,
            child: Container(
              width: 320.rpx,
              //height: 244.rpx,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
              ),
              child: Column(
                children: [
                  20.hspace,
                  UText.get("确认变更收货信息吗？", UIColor.color_black, 16.rpx,fw: FontWeight.bold),
                  20.hspace,
                  Container(height: 0.5.rpx, color: UIColor.color_divider),
                  widget.missionNum > 1?
                  TextButton(onPressed: () {
                    print("同步到所有任务");
                    changeDestination(1);
                  }, child: UText.get("同步到所有任务", UIColor.color_primary, 16.rpx)):0.wspace,
                  Container(height: 0.5.rpx, color: UIColor.color_divider),
                  TextButton(onPressed: () {
                    print("仅本任务变更");
                    changeDestination(0);
                  }, child: UText.get( widget.missionNum >1?"仅本任务变更":"变更收货信息", UIColor.color_primary, 16.rpx)),
                  Container(height: 0.5.rpx, color: UIColor.color_divider),
                  2.hspace,
                  MaterialButton(
                      child: UText.get("取消", UIColor.color_t13, 16.rpx,fw: FontWeight.bold),
                      onPressed: () {
                        Navigator.of(context).pop();
                        Toast.show(context, msg: "取消修改", seconds: 2);
                      }).size(56.rpx, double.infinity),
                ],
              ),
            ).intrinsicHeight
        );
      },
    );

  }

  void changeDestination(int type) {
    print(widget);
    var json = {};
    json["mission_no"] = (widget.no).toString();
    json["delivery_station_id"] = _stationId == ""?widget.stationId : _stationId;
    json["delivery_station_name"] = _stationName == ""?widget.stationName : _stationName;
    json["delivery_address"] = _address;
    json["delivery_station_alias_id"] = _aliasId== 0?widget.aliasId :_aliasId;
    json["delivery_station_alias_name"] = _aliasName== ""?widget.aliasName :_aliasName;
    json["is_all"] = type;
    json["delivery_username"] = _nameTextController.text;
    json["delivery_tel"] = _phoneTextController.text;
    json["delivery_addr_desc"] = _addDescTextController.text;
    json["delivery_car_plate"] = _carNoTextController.text;
    json["full"] = true;
    // json["delivery_station_alias_id"] = (station_id).toString();
    // json["delivery_station_alias_name"] = (station_id).toString();
    // json["is_all"] = (station_id).toString();
    // json["delivery_username"] = (station_id).toString();
    // json["delivery_tel"] = (station_id).toString();
    // json["delivery_addr_desc"] = (station_id).toString();
    // json["delivery_car_plate"] = (station_id).toString();
    // json["full"] = (station_id).toString();
    // 隐藏键盘
    Alib.hideKeyboard(context);
    var dialog = LoadingDialog(context);
    print(json);
    dialog.show(text: "同步中...");
    Api.submitx(context, "/waybill_mission/change_destination", data: json, progress: false, success: (data) {
      dialog.hide();
      Navigator.of(context).pop();
      eventBus.fire(RefreshOrderEvent());
      eventBus.fire(RefreshMapEvent());
      Toast.show(context, msg: "修改成功", seconds: 2);
    }, failTip: "提交失败", fail: (_) {
      dialog.hide();
    });
    Navigator.of(context).pop();
  }
}